package elastic

import org.elasticsearch.client.Requests
import play.api.Logger
import org.elasticsearch.common.xcontent.XContentFactory

object Tracer {

  val client = ElasticRuc.node.client()
  val indexName = "rucTracer"

  Tracer.createIndex()
  def createIndex() = {
    Logger.info("create Tracer index")
    val existsRequest = Requests.indicesExistsRequest(indexName)
    val existsResponse =
      client.admin().indices().exists(existsRequest).actionGet()
    Logger.info("existsResponse: " + existsResponse.exists())
    if (!existsResponse.exists()) {
      val createRequest = Requests.createIndexRequest(indexName)
      val createResponse =
        client.admin().indices().create(createRequest).actionGet()
      Logger.info("createResponse: " + createResponse)
    }
  }

  def trace(ruc: String, found: Long, responseTime: Long, ip: String) = {
  	Logger.info("trace ruc: " + ruc + ", found: " + found + ", responseTime: " + responseTime + ",ip: " + ip)
    val jsonBuilder = XContentFactory.jsonBuilder()
    val req = client.prepareIndex("ruc", "indexName", ruc)
      .setSource(jsonBuilder
        .startObject()
        .field("ruc", ruc)
        .field("found", found)
        .field("responseTime", responseTime)
        .field("ip", ip)
        .endObject())

    val result = req.execute().actionGet();

    val count = client.prepareCount(indexName).execute().actionGet()
    Logger.info("traces: " + count.count())

  }
}